package JAVA并发;

import java.util.concurrent.CountDownLatch;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.atomic.AtomicInteger;

/**
 * @author zhangmin
 * @create 2022-03-16 15:45
 * 非同步阻塞：J.U.C 包里面的整数原子类 AtomicInteger 的方法调用了 Unsafe 类的 CAS 操作。
 */
public class ThreadExample11_AtomicInteger {
    private AtomicInteger cnt=new AtomicInteger();

    public void add(){
        //自增操作
        cnt.incrementAndGet();
    }

    public int get(){
        return cnt.get();
    }

    public static void main(String[] args) throws InterruptedException {
        final int threadsize=1000;
        ThreadExample11_AtomicInteger e=new ThreadExample11_AtomicInteger();
        final CountDownLatch countDownLatch=new CountDownLatch(threadsize);
        ExecutorService executorService= Executors.newCachedThreadPool();
        for (int i = 0; i < threadsize; i++) {
            executorService.execute(()->{
                e.add();
                countDownLatch.countDown();
            });
        }
        countDownLatch.await();
        executorService.shutdown();
        System.out.println(e.get());
    }
}
